//
//  Utils.m
//  douniu
//
//  Created by dev on 2023/2/8.
//

#import "Utils.h"

@implementation Utils

/**
 * 设置本地存储
 */
+ (void)setLocalStorage:(NSString *)key value:(id)value {
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
}

/**
 * 获取本地存储
 */
+ (id)getLocalStorage:(NSString *)key {
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

/**
 * 判断用户是否登陆
 */
+ (BOOL)isLogin {
    return [Utils getUserToken]!=nil;
}

/**
 * 判断用户是否是付费会员
 */
+ (BOOL)isVip {
    NSDictionary *data = [Utils getUserData];
    if(!data) {
        return NO;
    }
    return [data[@"vip"] boolValue];
}

/**
 * 获取用户信息
 */
+ (NSDictionary *)getUserData {
    NSData *data = [Utils getLocalStorage:@"kUserData"];
    if(data==nil) {
        return nil;
    }
    return (NSDictionary*)[NSJSONSerialization JSONObjectWithData:[Utils getLocalStorage:@"kUserData"] options:NSJSONReadingMutableLeaves error:nil];
}

/**
 * 设置用户信息
 */
+ (void)setUserData:(NSDictionary *)userData {
    NSData *data = [NSJSONSerialization dataWithJSONObject:userData options:NSJSONWritingPrettyPrinted error:nil];
    [Utils setLocalStorage:@"kUserData" value:data];
}

/**
 * 移除用户信息
 */
+ (void)removeUserData {
    // 移除用户数据
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"kUserData"];
    // 移除用户TOKEN
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"kUserToken"];
}

/**
 * 设置用户TOKEN
 */
+ (void)setUserToken:(NSString *)userToken {
    return [Utils setLocalStorage:@"kUserToken" value:userToken];
}

/**
 * 获取用户TOKEN
 */
+ (NSString *)getUserToken {
    return [Utils getLocalStorage:@"kUserToken"];
}

+ (NSString *)getFullVersionName {
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSString *build = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    NSString *versionAndBuild = [NSString stringWithFormat:@"%@ (Build: %@)", version, build];
    return versionAndBuild;
}

+ (NSString *)getImageUrl:(NSString *)imageUrl {
    return [NSString stringWithFormat:@"%@%@", BASE_IMAGE_URL, imageUrl];
}

+ (NSString *)formatCoin:(NSInteger)coin {
    if(coin>0) {
        return [NSString stringWithFormat:@"%ld 红币", coin];
    } else {
        return @"免费";
    }
}

+ (NSString *)formatDate:(NSString *)dateTime format:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = nil;
    if(!dateTime) {
        date = [NSDate now];
    } else  {
        date = [dateFormatter dateFromString:dateTime];
    }
    // 初始化 NSDateFormatter
    NSDateFormatter *returnDateFormatter = [[NSDateFormatter alloc] init];
    // 设置日期格式（比如 "yyyy-MM-dd HH:mm:ss"）
    [returnDateFormatter setDateFormat:format];
    // 将 NSDate 转换为 NSString
    NSString *dateString = [returnDateFormatter stringFromDate:date];
    return dateString;
}

+ (NSString *)formatDate:(NSString *)dateTime {
    // 日期格式化器，用于将字符串转换为日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateTime];
    
    // 获取当前时间
    NSDate *now = [NSDate date];
    
    // 计算两个日期之间的时间差
    NSTimeInterval timeInterval = [now timeIntervalSinceDate:date];
    
    // 计算天、小时、分钟
    NSInteger days = timeInterval / (24 * 60 * 60);
    NSInteger hours = ((NSInteger)timeInterval % (24 * 60 * 60)) / (60 * 60);
    NSInteger minutes = ((NSInteger)timeInterval % (60 * 60)) / 60;
    
    // 如果超过1天，返回格式化日期
    if (days > 3) {
        // 格式化并返回日期（只显示日期，不显示时间差）
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        return [dateFormatter stringFromDate:date];
    } else if (days > 0  && days < 3)  {
        // 如果超过 1 天小于 3 天
        return [NSString stringWithFormat:@"%ld天前", (long)days];
    } else if (hours > 0) {
        // 如果超过1小时但不足1天，返回多少小时前
        return [NSString stringWithFormat:@"%ld小时前", (long)hours];
    } else if (minutes > 0) {
        // 如果不足1小时，返回多少分钟前
        return [NSString stringWithFormat:@"%ld分钟前", (long)minutes];
    } else {
        // 如果时间差小于1分钟，返回“刚刚”
        return @"刚刚";
    }
}

+ (NSString *)formatRemainDate:(NSString *)dateTime {
    if(dateTime.length==0) {
        return @"无截止限制";
    }
    NSDate *endDate = [self parseDate:dateTime];
    // 获取当前时间
    NSDate *now = [NSDate date];
    // 计算时间差
    NSTimeInterval timeInterval = [endDate timeIntervalSinceDate:now];
    // 如果时间差小于0，表示已经截止
    if (timeInterval < 0) {
        return @"已截止";
    }
    // 计算剩余的天、小时和分钟
    NSInteger days = timeInterval / (60 * 60 * 24); // 天
    NSInteger hours = ((NSInteger)(timeInterval / (60 * 60))) % 24; // 小时
    NSInteger minutes = ((NSInteger)(timeInterval / 60)) % 60; // 分钟
    // 返回格式化字符串
    return [NSString stringWithFormat:@"%ld天 %ld时 %ld分 后截止", (long)days, (long)hours, (long)minutes];
}

+ (NSInteger)formatRemainInterval:(NSString *)dateTime duration:(NSString*)duration {
    if(dateTime.length==0 && duration.length==0) {
        return 0;
    } else if(dateTime.length==0 && duration.length!=0) {
        return -[duration intValue];
    }
    NSDate *endDate = [self parseDate:dateTime];
    // 获取当前时间
    NSDate *now = [NSDate date];
    // 计算时间差
    NSTimeInterval timeInterval = [endDate timeIntervalSinceDate:now];
    // 转换为整数（秒）
    NSInteger integerTimeInterval = (NSInteger)timeInterval;
    return integerTimeInterval;
}

+ (NSString *)formatDayOfWeek:(NSString *)dateTime {
    NSDate *date = [self parseDate:dateTime];
    // 获取当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 设定日期的组成部分
    NSDateComponents *components = [calendar components:NSCalendarUnitWeekday fromDate:date];
    // 获取星期几，1是星期日，2是星期一，以此类推
    NSInteger weekday = [components weekday];
    // 数组包含对应的星期几的字符串
    NSArray *weekdays = @[@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六"];
    // 返回对应的星期几字符串
    return weekdays[weekday - 1];
}

+ (NSDate*)parseDate:(NSString*)dateTime {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateTime];
    return date;
}

+ (NSDate*)parseDate:(NSString*)dateTime format:(NSString*)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSDate *date = [dateFormatter dateFromString:dateTime];
    return date;
}

+ (NSString *)formatTimestamp:(NSInteger)timestamp format:(NSString *)format {
    // 将时间戳转换为 NSDate 对象
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
    // 创建 NSDateFormatter 实例
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置需要的日期格式（例如："yyyy-MM-dd HH:mm:ss"）
    formatter.dateFormat = format ? format : @"yyyy-MM-dd HH:mm:ss";
    // 将 NSDate 转换为指定格式的字符串
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}

@end
